package com.wangshidai.mapper.impl;

import com.wangshidai.entity.Dept;
import com.wangshidai.mapper.DeptMapper;
import com.wangshidai.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DeptMapperImpl implements DeptMapper {//持久层
    @Override
    public void saveDept(Dept dept) {
        try {
            Connection conn = DBHelper.getConn();

            //3. 写一个sql语句
            String sql="INSERT INTO `dept` (`deptName`, `address`) VALUES (?,?)";
            //4. 创建仓库管理员（陈述对象）
            PreparedStatement ps = conn.prepareStatement(sql);
            //5.给？赋值
            ps.setString(1,dept.getDeptName());
            ps.setString(2,dept.getAddress());
            //5. 仓库管理员执行sql
            ps.executeUpdate();
            //6. 关门
            DBHelper.close(ps,conn);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    @Override
    public void updateDept(Dept dept) {

    }

    @Override
    public void deleteDept(int did) {

    }

    @Override
    public List<Dept> queryDepts() {

        List<Dept> list=new ArrayList<>();
        try {
            Connection conn = DBHelper.getConn();
            String sql="SELECT did,deptName,address FROM `dept`";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();  //ResultSet 数据集合
            while (rs!=null&&rs.next()){
                //每次循环取出一行数据
                int did = rs.getInt("did");
                String deptName = rs.getString("deptName");
                String address = rs.getString("address");
                //将这行数据保存到小盒子dept中
                Dept dept=new Dept(did,deptName,address);
                //将dept保存到list中
                list.add(dept);

            }

            DBHelper.close(rs,ps,conn);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }
}
